package com.atguigu.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.config.AlipayConfig;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.PaymentType;
import com.atguigu.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.alipay.api.AlipayConstants.SIGN_TYPE;
import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * <p>
 * 支付信息表 前端控制器
 * </p>
 *
 * @author linjiang
 * @since 2022-08-09
 */
@RestController
@RequestMapping("/payment")
public class PaymentInfoController {
    @Autowired
    private PaymentInfoService paymentInfoService;

    //1.创建支付二维码
    @RequestMapping("createQrCode/{orderId}")
    public String createQrCode(@PathVariable Long orderId) throws Exception {
      String from =paymentInfoService.createQrCode(orderId);
        System.out.println("form: "+from);
      return from;
    }
    //2.支付成功之后支付宝调用我们的地址
    //将异步通知中收到的所有参数都存放到map中 mapB
    @PostMapping("/async/notify")
    public String asyncNotify(@RequestParam Map<String,String> aliPayParam) throws Exception {
        System.out.println("阿里云的参数："+aliPayParam);
        //判断是不是阿里云发的接口
        boolean signVerified = AlipaySignature.rsaCheckV1(aliPayParam, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        String tradeStatus = aliPayParam.get("trade_status");
        String outTradeNo = aliPayParam.get("out_trade_no");
        //TRADE_SUCCESS 或 TRADE_FINISHED
        if(signVerified){
            if("TRADE_SUCCESS".equals(tradeStatus)||"TRADE_FINISHED".equals(tradeStatus)){
                 // 验签成功后 校验失败返回failure
                PaymentInfo paymentInfo= paymentInfoService.getPaymentInfo(outTradeNo);
                //如果支付表信息已经支付过或者关闭了 就不需要再执行了
                if (paymentInfo.getPaymentStatus().equals(PaymentStatus.ClOSED.name())|| paymentInfo.getPaymentStatus().equals(PaymentStatus.PAID.name())){
                    return "success";
                }
                //进行修改 支付订单信息
                paymentInfoService.updatePaymentInfo(outTradeNo, PaymentType.ALIPAY.name(),aliPayParam);

                return "success";

            }

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
        return "failure";
    }





   /**1.退款接口
    a.出现二维码 未支付 不能退款
    b.出现二维码 已支付 能退款
    **/
   @GetMapping("reFundAliPayTrade/{orderId}")
    public boolean reFundAliPayTrade(@PathVariable Long orderId) throws AlipayApiException {
     return paymentInfoService.reFundAliPayTrade(orderId);
   }
    /**
     * 	2.查询支付宝是否有交易记录接口
     *     a.出现二维码 没有扫描 没有交易记录
     *     b.出现二维码 有扫描   有交易记录
     */
    @GetMapping("queryAliPayTrade/{orderId}")
    public boolean queryAliPayTrade(@PathVariable Long orderId) throws AlipayApiException {
        return paymentInfoService.queryAliPayTrade(orderId);
    }
    /**
     * 	3.交易关闭
     *     a.出现二维码 未支付 可以关闭交易
     *     b.出现二维码 已支付 不能关闭交易
     */
    @GetMapping("closeAliPayTrade/{orderId}")
    public boolean closeAliPayTrade(@PathVariable Long orderId) throws AlipayApiException {
        return paymentInfoService.closeAliPayTrade(orderId);
    }
    @GetMapping("getAliPayTrade/{outTradeNo}")
    public PaymentInfo getAliPayTrade(@PathVariable String outTradeNo) throws AlipayApiException {
        return paymentInfoService.getPaymentInfo(outTradeNo);
    }
}

